//
//  HomeMiddleLiveViewController.m
//  CYWFrame
//
//  Created by 于顺燊 on 2018/8/14.
//  Copyright © 2018年 Macx. All rights reserved.
//

#import "HomeMiddleLiveViewController.h"
#import "SimpleLiveInfo.h"
#import "HomeMiddleLiveTableViewCell.h"
#import "LiveRoomViewControllerAudience.h"
#import "LiveRoomViewController.h"

#import "TCPlayViewController.h"
#import "TCPlayViewController_LinkMic.h"

#import "Live.h"

@interface HomeMiddleLiveViewController ()<UITableViewDelegate, UITableViewDataSource, LiveRoomVCADelegate>

@property (strong, nonatomic)UITableView *tableView;
@property (strong ,nonatomic) NSMutableArray *liveArray;

//AgoraLive
@property (assign, nonatomic) AgoraVideoProfile videoProfile;
@property (assign, nonatomic) AgoraClientRole clientRole;

@property (nonatomic, retain) TCPlayViewController *playVC;
@property (nonatomic, retain) LiveRoomViewControllerAudience *liveRoomVCAudience;

@end

@implementation HomeMiddleLiveViewController {
	BOOL             _hasEnterplayVC; // 直播间
}

-(void)viewWillAppear:(BOOL)animated
{
	[self getLiveInfo];
}

- (void)viewDidLoad {
	[super viewDidLoad];
	self.videoProfile = AgoraVideoProfileLandscape480P;
	self.clientRole = AgoraClientRoleAudience;
	[self buildUI];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
	// Dispose of any resources that can be recreated.
}

- (void)buildUI
{
	_tableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, SCREEN_WIDTH-40, 170) style:UITableViewStylePlain];
	[_tableView registerNib:[UINib nibWithNibName:@"HomeMiddleLiveTableViewCell" bundle:nil] forCellReuseIdentifier:@"HomeMiddleLiveCell"];
	_tableView.delegate = self;
	_tableView.dataSource = self;
	_tableView.scrollEnabled = NO;
	_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	[self.view addSubview:_tableView];
}

- (void)getLiveInfo
{
	[[NetworkTool sharedTool] requestWithName:@"获取首页中间推荐信息(直播)" URLString:APIRecommendIndex parameters:nil method:@"POST" callBack:^(id responseObject) {
		
		//NSError *error = nil;
		NSArray *array = responseObject[@"data"][@"live"];
		[self.liveArray removeAllObjects];
		for (NSDictionary *dict in array)
		{
			SimpleLiveInfo *model = [[SimpleLiveInfo alloc] init];
			[model setValuesForKeysWithDictionary:dict];
			[self.liveArray addObject:model];
		}
		[self.tableView reloadData];
		if (self.liveArray) {
			NSLog(@"有%ld个数据", self.liveArray.count);
			[self.tableView reloadData];
			
		}
		else
			NSLog(@"没有拿到中间直播信息");
	}];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	HomeMiddleLiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomeMiddleLiveCell"];
	[cell setModel:self.liveArray[indexPath.row]];
	[cell.joinLiveButton addActionWithblock:^{
		[self PUTLive:cell.model.user_id];
	}];
	cell.selectionStyle = UITableViewCellSelectionStyleNone;
	
	return cell;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 120;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 120;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return self.liveArray.count;
}

-(NSMutableArray *)liveArray
{
	if (!_liveArray) {
		_liveArray = [[NSMutableArray alloc] init];
	}
	return _liveArray;
}

/**
 进入直播间
 */
- (void)PUTLive:(NSString *)userId {
	
	if (GetUserDefaule(USERINFO) == NULL) {
		[self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
		return;
	}
	
	// PUT /users/{uid}/lives 进入直播间 只有主播进入都会有推流地址 uid * 主播ID
	NSString *url = [APIUser stringByAppendingFormat:@"/%@/lives", userId];
	
	[[NetworkTool sharedTool] requestWithName:@"进入直播间" URLString:url parameters:nil method:@"PUT" callBack:^(id responseObject) {
		
		if ([[GetUserDefaule(USERINFO) valueForKey:@"user_id"] isEqualToString:userId]) {
			NSLog(@"这个直播是自己的直播，走创建直播流程");
			
			[LZCTools HUDMessage:@"该直播间已关播" delay:1.0];
			return;
			//本来想做一个优化如果是自己的直播间就续播那样，不过貌似有问题，先注释
			/*
			self.clientRole = AgoraClientRoleBroadcaster;
			Live *model = [[Live alloc] init];
			[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
			
			
			TCLiveInfo *info = [[TCLiveInfo alloc] init];
			info.userinfo = [[TCLiveUserInfo alloc] init];
			
			info.userid = [model.anchor valueForKey:@"user_id"];
			info.groupid = model.chatroom_id;
			info.likecount = [model.like_num intValue];
			info.title = model.title;
			//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
			info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
			info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
			info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
			info.timestamp = [model.start_time intValue];
			info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
			info.userinfo.headpic = [model.anchor valueForKey:@"face"];
			info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
			info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
			//        info.money = [model.anchor valueForKey:@"money"];
			info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
			info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
			
			info.viewercount = (int)model.viewer_num;
			info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
			
			//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
			
			info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
			info.myuserid = [model.anchor valueForKey:@"user_id"];
			
			
			// 保存直播信息，后面用到
			NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
			SetUserDefaule(live, CURRLIVE);
			
			NSDictionary *userinfo = GetUserDefaule(USERINFO);
			
			NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
									   @"uid":[userinfo valueForKey:@"user_id"],
									   @"nickname":[userinfo valueForKey:@"nickname"],
									   @"headpic":[userinfo valueForKey:@"face"],
									   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
			
			
			NSError *parseError = nil;
			NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
			NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
			
			info.senderInfo = infoStr;
			UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
			LiveRoomViewController *agoraLiveRoomVC = (LiveRoomViewController *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVC"];
			agoraLiveRoomVC.channelId = info.groupid;
			agoraLiveRoomVC.liveInfo = info;
			agoraLiveRoomVC.videoProfile = self.videoProfile;
			agoraLiveRoomVC.clientRole = self.clientRole;
			agoraLiveRoomVC.isEnterSelf = 1;
			UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:agoraLiveRoomVC];
			
			// 设置导航背景风格颜色
			nav.navigationBar.barTintColor = UIMainColorRGB;
			[nav.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:kWhiteColor}];
			
			[self presentViewController:nav animated:YES completion:nil];
			*/
		}
		else {
			Live *model = [[Live alloc] init];
			[model setValuesForKeysWithDictionary:[responseObject valueForKey:@"data"]];
			
			
			TCLiveInfo *info = [[TCLiveInfo alloc] init];
			info.userinfo = [[TCLiveUserInfo alloc] init];
			
			info.userid = [model.anchor valueForKey:@"user_id"];
			info.groupid = model.chatroom_id;
			info.likecount = [model.like_num intValue];
			info.title = model.title;
			//        info.playurl = model.pull_url[0]; // rtmp 默认第一个
			info.playurl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"]; //拉流地址，键名后缀代表清晰度，无则代表原画 lud-超清 lhd-高清 lsd-标清 lld-流畅，如rtmp_lud:’rtmp://xxx’,代表超清的rtmp 默认标清，切换超清
			info.biaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lsd"];
			info.gaoUrl = [model.pull_multi_urls valueForKey:@"rtmp_lud"];
			info.timestamp = [model.start_time intValue];
			info.userinfo.nickname = [model.anchor valueForKey:@"nickname"];
			info.userinfo.headpic = [model.anchor valueForKey:@"face"];
			info.userinfo.frontcover = [model.anchor valueForKey:@"face"];
			info.isLike = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"is_like"]];
			//        info.money = [model.anchor valueForKey:@"money"];
			info.money = [NSString stringWithFormat:@"%ld", model.stars_count];
			info.isPraise = [NSString stringWithFormat:@"%ld", model.is_like];
			
			info.viewercount = (int)model.viewer_num;
			info.roomid = [NSString stringWithFormat:@"%ld", (long)model.liveId];
			
			//        info.isVip = [self.liveData[@"anchor"] valueForKey:@"is_enterprise"];
			
			info.isVip = [NSString stringWithFormat:@"%@", [model.anchor valueForKey:@"role"]];
			info.myuserid = [model.anchor valueForKey:@"user_id"];
			
			
			// 保存直播信息，后面用到
			NSDictionary *live = @{@"hostId":info.userid, @"groupId":info.groupid};
			SetUserDefaule(live, CURRLIVE);
			
			NSDictionary *userinfo = GetUserDefaule(USERINFO);
			
			NSDictionary *infoDict = @{@"imId":[userinfo valueForKey:@"user_id"],
									   @"uid":[userinfo valueForKey:@"user_id"],
									   @"nickname":[userinfo valueForKey:@"nickname"],
									   @"headpic":[userinfo valueForKey:@"face"],
									   @"level":[NSString stringWithFormat:@"%@", [userinfo valueForKey:@"level"]]};
			
			
			NSError *parseError = nil;
			NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
			NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
			
			info.senderInfo = infoStr;
			
			if (_liveRoomVCAudience == nil) {
				UIStoryboard *agoraSB = [UIStoryboard storyboardWithName:@"AgoraLive" bundle:nil];
				_liveRoomVCAudience = (LiveRoomViewControllerAudience *)[agoraSB instantiateViewControllerWithIdentifier:@"AgoraLiveRoomVCA"];
				_liveRoomVCAudience.channelId = info.groupid;
				_liveRoomVCAudience.clientRole = self.clientRole;
				_liveRoomVCAudience.videoProfile = self.videoProfile;
				_liveRoomVCAudience.delegate = self;
				_liveRoomVCAudience.liveInfo = info;
			}
			
			[self.navigationController pushViewController:_liveRoomVCAudience animated:YES];
		}
	}];
}

//MARK: - AgoraLive delegates

- (void)liveVCNeedClose:(LiveRoomViewControllerAudience *)liveVC {
	[self.navigationController popViewControllerAnimated:YES];
	_liveRoomVCAudience = nil;
	self.clientRole = AgoraClientRoleAudience;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
